import { getCurrentPageRoute } from './pageUtil'
import { getValue } from './valueUtil'

const contextCached = {}

function pagedContext (pageRoute = null) {
  if (!pageRoute) {
    pageRoute = getCurrentPageRoute()
  }
  const route = '__route: ' + pageRoute
  if (!contextCached[route]) {
    contextCached[route] = {}
  }
  return contextCached[route]
}

export function printContextCached () {
  console.log(contextCached)
}

function globalContext () {
  return contextCached
}

export function getContext (key, route = '') {
  const context = pagedContext(route)
  return context[key]
}

export function getContextOrSetDefault (key, defaultValue, route = '') {
  const context = pagedContext(route)
  if (!context[key]) {
    context[key] = getValue(defaultValue)
  }
  return context[key]
}

export function removeContext (key, route = '') {
  const context = pagedContext(route)
  delete context[key]
}

export function clearContext (route) {
  const routeKey = '__route: ' + route
  if (contextCached[routeKey]) {
    delete contextCached[routeKey]
  }
}

export function takeContext (key) {
  const result = getContext(key)
  if (typeof result !== 'undefined') {
    removeContext(key)
  }
  return result
}

export function setContext (key, value, route = '') {
  const context = pagedContext(route)
  context[key] = value
}

export function getGlobalContext (key) {
  const context = globalContext()
  return context[key]
}

export function removeGlobalContext (key) {
  const context = globalContext()
  delete context[key]
}

export function takeGlobalContext (key) {
  const result = getGlobalContext(key)
  if (typeof result !== 'undefined') {
    removeGlobalContext(key)
  }
  return result
}

export function setGlobalContext (key, value) {
  const context = globalContext()
  context[key] = value
}